<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学期" prop="semester">
        <el-input
          v-model="queryParams.semester"
          placeholder="请输入学期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.schedule_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['academic:scheduleTask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-magic-stick"
          size="mini"
          @click="handleIntelligentSchedule"
          v-hasPermi="['academic:scheduleTask:intelligent']"
        >智能排课</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['academic:scheduleTask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['academic:scheduleTask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['academic:scheduleTask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="id" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="学期" align="center" prop="semester" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="small">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" prop="progress">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.progress" :color="getProgressColor"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['academic:scheduleTask:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['academic:scheduleTask:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="handleStartTask(scope.row)"
            v-hasPermi="['academic:scheduleTask:start']"
          >开始</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleCompleteTask(scope.row)"
            v-hasPermi="['academic:scheduleTask:complete']"
          >完成</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排课任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="学期ID" prop="semesterId">
          <el-input-number v-model="form.semesterId" :min="1" placeholder="请输入学期ID" />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-input v-model="form.semester" placeholder="请输入学期" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog :title="'任务详情 - ' + (currentTask ? currentTask.taskName : '')" :visible.sync="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ currentTask ? currentTask.id : '' }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ currentTask ? currentTask.taskName : '' }}</el-descriptions-item>
        <el-descriptions-item label="学期">{{ currentTask ? currentTask.semester : '' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentTask ? currentTask.status : 0)" size="small">
            {{ getStatusText(currentTask ? currentTask.status : 0) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="进度">
          <el-progress 
            :percentage="currentTask ? currentTask.progress : 0" 
            :color="getProgressColor(currentTask ? currentTask.progress : 0)"
            :format="formatProgress"
          />
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentTask ? currentTask.startTime : '' }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentTask ? currentTask.endTime : '' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentTask ? currentTask.remark : '' }}</el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px;">
        <h4>执行日志</h4>
        <el-card shadow="never" style="max-height: 300px; overflow-y: auto;">
          <div v-for="(log, index) in executionLogs" :key="index" class="log-item">
            <span class="log-time">{{ log.time }}</span>
            <el-tag :type="log.level === 'ERROR' ? 'danger' : 'info'" size="mini">{{ log.level }}</el-tag>
            <span class="log-message">{{ log.message }}</span>
          </div>
          <div v-if="executionLogs.length === 0" style="text-align: center; color: #909399;">
            暂无执行日志
          </div>
        </el-card>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetail">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScheduleTask, getScheduleTask, delScheduleTask, addScheduleTask, updateScheduleTask, startScheduleTask, completeScheduleTask, exportScheduleTask, intelligentSchedule } from "@/api/academic/scheduleTask";

export default {
  name: "ScheduleTask",
  dicts: ['schedule_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排课任务表格数据
      scheduleTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        semester: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        semesterId: [
          { required: true, message: "学期ID不能为空", trigger: "blur" }
        ],
        semester: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
      },
      // 刷新定时器
      refreshTimer: null,
      // 任务详情对话框
      detailOpen: false,
      // 当前任务详情
      currentTask: null,
      // 执行日志
      executionLogs: []
    };
  },
  created() {
    this.getList();
    // 启动定时器，每5秒刷新一次任务状态
    this.refreshTimer = setInterval(() => {
      this.refreshRunningTasks();
    }, 5000);
  },
  beforeDestroy() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
  methods: {
    /** 查询排课任务列表 */
    getList() {
      this.loading = true;
      listScheduleTask(this.queryParams).then(response => {
        this.scheduleTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    
    /** 刷新运行中的任务 */
    refreshRunningTasks() {
      const runningTasks = this.scheduleTaskList.filter(task => task.status === 1);
      if (runningTasks.length > 0) {
        listScheduleTask({
          pageNum: 1,
          pageSize: 100,
          status: 1
        }).then(response => {
          const updatedTasks = response.rows;
          updatedTasks.forEach(updatedTask => {
            const index = this.scheduleTaskList.findIndex(task => task.id === updatedTask.id);
            if (index !== -1) {
              this.$set(this.scheduleTaskList, index, updatedTask);
            }
          });
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        semesterId: null,
        semester: null,
        status: 0,
        progress: 0,
        startTime: null,
        endTime: null,
        errorMessage: null,
        configData: null,
        resultData: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排课任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getScheduleTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改排课任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScheduleTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScheduleTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除排课任务编号为"' + ids + '"的数据项？').then(function() {
        return delScheduleTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有排课任务数据项？').then(function() {
        return exportScheduleTask(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(() => {});
    },
    /** 开始任务 */
    handleStartTask(row) {
      const id = row.id;
      this.$modal.confirm('是否确认开始排课任务"' + row.taskName + '"？').then(function() {
        return startScheduleTask(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("任务已开始");
      }).catch(() => {});
    },
    /** 完成任务 */
    handleCompleteTask(row) {
      const id = row.id;
      this.$modal.confirm('是否确认完成排课任务"' + row.taskName + '"？').then(function() {
        return completeScheduleTask(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("任务已完成");
      }).catch(() => {});
    },
    /** 获取进度条颜色 */
    getProgressColor(percentage) {
      if (percentage < 30) return '#f56c6c';
      if (percentage < 70) return '#e6a23c';
      return '#67c23a';
    },
    
    /** 查看任务详情 */
    handleViewDetail(row) {
      this.currentTask = { ...row };
      this.detailOpen = true;
      // 模拟执行日志
      this.executionLogs = [
        { time: new Date().toLocaleString(), level: 'INFO', message: `任务 ${row.taskName} 开始执行` },
        { time: new Date().toLocaleString(), level: 'INFO', message: '正在加载课程数据...' },
        { time: new Date().toLocaleString(), level: 'INFO', message: '正在分析排课约束...' },
        { time: new Date().toLocaleString(), level: 'INFO', message: '正在执行遗传算法...' }
      ];
    },
    
    /** 关闭详情对话框 */
    closeDetail() {
      this.detailOpen = false;
      this.currentTask = null;
      this.executionLogs = [];
    },
    
    /** 获取状态标签类型 */
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      };
      return statusMap[status] || 'info';
    },
    
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '进行中',
        2: '已完成',
        3: '已失败'
      };
      return statusMap[status] || '未知';
    },
    /** 智能排课 */
    handleIntelligentSchedule() {
      this.$prompt('请输入学期ID', '智能排课', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '学期ID必须是数字'
      }).then(({ value }) => {
        const semesterId = parseInt(value);
        this.$modal.confirm('是否确认开始智能排课？此操作将清除该学期现有课表并重新生成。').then(() => {
          this.loading = true;
          return intelligentSchedule(semesterId);
        }).then(response => {
          this.$modal.msgSuccess("智能排课任务已启动，请稍后查看结果");
          this.getList();
        }).catch(error => {
          this.$modal.msgError("智能排课失败：" + (error.message || '未知错误'));
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {});
    },
    
    /** 格式化进度显示 */
    formatProgress(percentage) {
      return percentage === 100 ? '完成' : `${percentage}%`;
    }
  }
};
</script>

<style scoped>
.mr3 {
  margin-right: 3px;
}

.log-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  min-width: 150px;
}

.log-message {
  margin-left: 10px;
  color: #606266;
}

.el-descriptions-item__label {
  font-weight: bold;
}

.el-progress__text {
  font-size: 12px;
}
</style>